Sort characters by frequency

Time: O(N); Space: O(N); medium

Example 1:

Input: s = “tree”

Output: “eert”

Explanation:

  • ‘e’ appears twice while ‘r’ and ‘t’ both appear once.

  • So ‘e’ must appear before both ‘r’ and ‘t’. Therefore “eetr” is also a valid answer.

Example 2:

Input: s = “cccaaa”

Output: “cccaaa”

Explanation:

  • Both ‘c’ and ‘a’ appear three times, so “aaaccc” is also a valid answer.

  • Note that “cacaca” is incorrect, as the same characters must be together.

Example 3:

Input: s = “Aabb”

Output: “bbAa”

Explanation:

  • “bbaA” is also a valid answer, but “Aabb” is incorrect.

  • Note that ‘A’ and ‘a’ are treated as two different characters.

[5]:
import collections

class Solution1(object):
    def frequencySort(self, s) -> str:
        """
        :type s: str
        :rtype: str
        """
        freq = collections.defaultdict(int)
        for c in s:
            freq[c] += 1
        # freq: {'t': 1, 'r': 1, 'e': 2}

        counts = [""] * (len(s) + 1)
        for c in freq:
            counts[freq[c]] += c       # add char to frequency backet
        # counts: ['', 'tr', 'e', '', '']
        #           0   1     2    3   4
        # sort items ???

        result = ""
        for count in reversed(range(len(counts) - 1)):
            for c in counts[count]:
                result += c * count

        return result
[6]:
sol = Solution1()
s = 'tree'
assert sol.frequencySort(s) == 'eetr'
s = 'cccaaa'
assert sol.frequencySort(s) == 'cccaaa'
s = 'Aabb'
assert sol.frequencySort(s) == 'bbAa'
[8]:
class Solution2(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        counts = [[s.count(c), c] for c in set(s)]

        counts.sort(reverse=True)

        return ''.join([c * count for c, count in counts])
[9]:
sol = Solution2()
s = 'tree'
assert sol.frequencySort(s) == 'eetr'
s = 'cccaaa'
assert sol.frequencySort(s) == 'cccaaa'
s = 'Aabb'
assert sol.frequencySort(s) == 'bbAa' or 'bbaA'